package com.ims.repository;

import com.b2c.common.third.thymeleaf.PagingResponse;
import com.b2c.common.utils.DateUtil;
import com.ims.entity.MediaDataReportEntity;
import com.ims.entity.WorkDailyEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Repository
public class WorkDailyRepository {
    @Autowired
    private JdbcTemplate jdbcTemplate;


    public void addDaily(WorkDailyEntity daily) {
        String sql = "INSERT INTO work_daily (userId,`type`,workYear,workDay,summary,plan,suggest,tag,createTime) VALUE (?,?,?,?,?,?,?,?,?)";
        String year= DateUtil.unixTimeStampToDate(System.currentTimeMillis() / 1000,"yyyy");

        jdbcTemplate.update(sql,daily.getUserId(),0, year,new Date(),daily.getSummary(),daily.getPlan(),daily.getSuggest(),daily.getTag(),System.currentTimeMillis() / 1000);
    }


    @Transactional
    public PagingResponse<WorkDailyEntity> getListByUserId(int pageIndex, int pageSize, Integer userId) {
        StringBuffer sb = new StringBuffer();
        sb.append("SELECT SQL_CALC_FOUND_ROWS * ");
        sb.append(" FROM work_daily ");
        sb.append(" where userId=? ");

        List<Object> params = new ArrayList<>();
        params.add(userId);


        sb.append(" ORDER BY id DESC LIMIT ?,?");
        params.add((pageIndex - 1) * pageSize);
        params.add(pageSize);

        var list = jdbcTemplate.query(sb.toString(),new BeanPropertyRowMapper<>(WorkDailyEntity.class),params.toArray(new Object[params.size()]));

        int total = jdbcTemplate.queryForObject("SELECT FOUND_ROWS() as row_num;", int.class);

//        for (var item:list) {
//            item.setItems(jdbcTemplate.query("SELECT * FROM media_data_report_item WHERE reportId=?",new BeanPropertyRowMapper<>(MediaDataReportItemEntity.class),item.getId()));
//        }

        return new PagingResponse<>(pageIndex, pageSize, total, list);
    }
}
